package com.twm.tamauth.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.twm.tamauth.R
import com.twm.tamauth.model.Affirmation


class MyAuthItemAdapter(
    private val context: Context,
    private val dataset: List<Affirmation>
) : RecyclerView.Adapter<MyAuthItemAdapter.ItemViewHolder>() {

    private var itemClickListener: ItemClickListener? = null

    fun setItemClickListener(listener: ItemClickListener) {
        itemClickListener = listener
    }

    interface ItemClickListener {
        fun onItemClick(itemText: String)
    }

    class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val imageView: ImageView = view.findViewById(R.id.item_image)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val adapterLayout = LayoutInflater.from(parent.context)
            .inflate(R.layout.list_item, parent, false)
        return ItemViewHolder(adapterLayout)
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val item = dataset[position]

        // Set image resource using setImageResource (example, replace with your actual logic)
        holder.imageView.setImageResource(item.imageResourceId)

        // Calculate the aspect ratio of the loaded image and adjust height
        val drawable = holder.imageView.drawable
        if (drawable != null) {
            val imageWidth = drawable.intrinsicWidth
            val imageHeight = drawable.intrinsicHeight

            // Calculate aspect ratio and adjust height
            if (imageWidth > 0 && imageHeight > 0) {
                val aspectRatio = imageWidth.toFloat() / imageHeight
                val newHeight =
                    (holder.itemView.resources.displayMetrics.widthPixels / aspectRatio).toInt()

                // Set the new height for the ImageView
                holder.imageView.layoutParams.height = newHeight
                holder.imageView.requestLayout() // Ensure the layout gets updated
            }
        }
    }

    override fun getItemCount() = dataset.size
}
